from .import constants
from django.http import HttpResponse
from django.shortcuts import render
import logging
from user.models import User
from utils.json_res import json_response
# Create your views here.
# 日志器
from utils.captcha.captcha import captcha

logger = logging.getLogger('django')


def image_code_view(request):
    """
    生成图片验证码
    :param request:
    url  :image_code/
    :return:
    """
    text, image = captcha.generate_captcha()
    request.session['image_code'] = text
    # 将验证码存入session中
    request.session.set_expiry(constants.IMAGE_CODE_EXPIRES)
    logger.info('Image code:{}'.format(text))

    return HttpResponse(content=image, content_type='image/jpg')

def check_username_view(rewquest,username):
    data = {

        'data':{
            'username':username,
            'count': User.objects.filter(username=username).count()
        }

    }
    print(username)
    return json_response(data)

def check_mobile_view(request, mobile):
    """
    校验手机号是否存在
    url:/moblie/(?P<moblie>1[3-9]\d{9})/
    :param request:
    :param username:
    :return:
    """
    data = {
        'mobile': mobile,
        'count': User.objects.filter(mobile=mobile).count()
    }

    return json_response(data=data)